// render.jsx
import { defineComponent,ref,onMounted,onBeforeUnmount,Teleport } from 'vue'

function randomNumber(start, end) {
  return start + Math.random() * (end - start);
}

const Rain = defineComponent({
  props:{
    delay:{
      type:Number,
      default:30
    }
  },
  setup(props) {
    const saveRef = ref(null);
    const start = ref([0, 0]);
    const end = ref([0, 0]);
    const endTime = ref(0);


    function init(){
      const { innerWidth, innerHeight } = window;
      const startX = randomNumber(0, innerWidth);
      const startY = -30;
      start.value = [startX, startY];
      const endX = randomNumber(0, innerWidth);
      const endY = innerHeight + 30;
      end.value = [endX, endY];
      endTime.value = randomNumber(3, 3.5) * 1000;
    } 
    init()
    onMounted(()=>{
      const { delay } = props;
      setTimeout(() => {
          if (saveRef.value) {
            saveRef.value.style.left = `${end.value[0]}px`;
            saveRef.value.style.top = `${end.value[1]}px`;
          }
          setTimeout(() => {
              if (saveRef.value) {
                saveRef.value.style.display = 'none';
              }
          }, endTime.value);
      }, delay);
    })
    const render = () => {
      console.log('===start==',start.value[0],start.value[1])
        return  <span ref={saveRef} className="rain" style={{
          left: `${start.value[0]}px`,
          top: `${start.value[1]}px`,
          transition: `all ${endTime.value / 1000}s`,
          transitionTimingFunction: 'linear',
          fontSize: '20px'
      }}>
          ❤️
      </span>
    }
    return render
  }
})


export default defineComponent({
  props:{
    num:{
      type:Number,
      default:30
    }
  },
  setup(props,context){
    const container = ref(null);
    const queue = ref([]);

    function init(){
      const rainNum = props.num;
      for (let i = 0; i < rainNum; i++) {
          const delay = randomNumber(i * 200, i * 200 + 1000);
          queue.value.push(<Rain key={i} delay={delay}/>);
      }
    }

    init()


    onMounted(()=>{
      
    })

    onBeforeUnmount(()=>{
      queue.value = null;
    })
    
    const render = () => {
      return <Teleport to="body">
        <div><div>{  queue.value }</div></div>
      </Teleport>
    }
    return render
  }
})